package hello.app.model;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import hello.app.model.data.Comment;

public class CommentModel implements Model<Comment>{

	private DataSource mDataSource = null;
	private Comment[] mData;

	CommentModel(Context context) {
		mDataSource = DataSource.getInstance(context);
    }

	public Comment[] find(String[] fields, String conditions, String order) {
		SQLiteDatabase db = mDataSource.getWritableDatabase();
		Comment[] comments = null;
        try {
        	Cursor cursor = db.query(
        			Comment.TABLE_NAME,
            		fields,
            		conditions,
            		null,
            		null,
            		null,
            		order);
        	int count = cursor.getCount();
        	comments = new Comment[count];
            cursor.moveToFirst();
            for(int i = 0; i < count; i++){
            	comments[i] = getComment(cursor);
                cursor.moveToNext();
            }
            this.mData = comments;
        } catch(Exception e){
        	comments = new Comment[0];
        } finally {
            db.close();
        }
		return comments;
	}

	public Comment[] findAll() {
		SQLiteDatabase db = mDataSource.getReadableDatabase();
		Comment[] comments = null;
		try {
	            Cursor cursor = db.query(Comment.TABLE_NAME, null, null, null, null, null, Comment.ID);
	            int count = cursor.getCount();
	            comments = new Comment[count];
	            cursor.moveToFirst();
	            for(int i = 0; i < count; i++){
	            	comments[i] = getComment(cursor);
	                cursor.moveToNext();
	            }
	            this.mData = comments;
	        } catch(Exception e){
	        	comments = new Comment[0];
	        } finally {
	            db.close();
	        }
		return comments;
	}

	public boolean save(Comment data) {
		boolean newData = false;
		if(findById(data.getId()) == null){
			newData = true;
		}
		SQLiteDatabase db = mDataSource.getWritableDatabase();
		boolean saved = false;
        try {
        	ContentValues values = new ContentValues();
        	values.put(Comment.ID, data.getId());
        	values.put(Comment.CONTACT_ID, data.getContactId());
        	values.put(Comment.USER_ID, data.getUserId());
        	values.put(Comment.USER_EMAIL, data.getUserEmail());
        	values.put(Comment.TEXT, data.getText());
        	values.put(Comment.GOOD, data.getGood());
        	values.put(Comment.BAD, data.getBad());
        	values.put(Comment.CREATED_AT, data.getCreatedAt());
        	values.put(Comment.UPDATED_AT, data.getUpdatedAt());
            // IDがnullの場合はinsert
            if(newData){
            	db.insert(Comment.TABLE_NAME, null, values);
            }else{
                db.update(Comment.TABLE_NAME, values, Comment.ID + "=?", new String[]{ String.valueOf(data.getId())});
            }
            this.mData = new Comment[1];
            mData[0] = data;
            saved = true;
        }catch(Exception e){
        	//Debug.log(e.getMessage());
        }finally {
            db.close();
        }
		return saved;
	}

	public boolean delete(long id) {
		boolean ret = false;
		SQLiteDatabase db = mDataSource.getReadableDatabase();
		try {
			db.delete(Comment.TABLE_NAME, Comment.ID + " = " + String.valueOf(id), null);
			ret = true;
		} finally {
			db.close();
		}
		return ret;
	}

	public Comment findById(long id) {
		SQLiteDatabase db = mDataSource.getReadableDatabase();

		Comment comment = null;
        try {
            Cursor cursor = db.query( Comment.TABLE_NAME, null, Comment.ID + "=?", new String[]{ String.valueOf(id)}, null, null, null);
            cursor.moveToFirst();
            comment = getComment(cursor);
        } catch(Exception e){
        	//Debug.error(e.getMessage());
        } finally {
            db.close();
        }
        return comment;
	}

	public Comment findUnique(String contact_id, String user_id) {
		SQLiteDatabase db = mDataSource.getReadableDatabase();

		Comment comment = null;
        try {
        	String sql = String.format("select * from %s where %s=%s AND %s=%s",
        			Comment.TABLE_NAME, Comment.CONTACT_ID, contact_id, Comment.USER_ID, user_id);
        	//String[] args = {Comment.TABLE_NAME, contact_id, user_id};
        	Cursor cursor = db.rawQuery(sql , null);
            //Cursor cursor = db.query( Comment.TABLE_NAME, null, where, args, null, null, null);
            cursor.moveToFirst();
            comment = getComment(cursor);
        } catch(Exception e){
        	//Debug.log(e.getMessage());
        } finally {
            db.close();
        }
        return comment;
	}
	public Comment findUnique(int contact_id, int user_id) {
		return findUnique(Integer.toString(contact_id),Integer.toString(user_id));
	}

	public Comment[] findByContactId(String id) {
		SQLiteDatabase db = mDataSource.getReadableDatabase();

		Comment[] comments = null;
        try {
            Cursor cursor = db.query( Comment.TABLE_NAME, null, Comment.CONTACT_ID + "=?", new String[]{ id}, null, null, null);
            int count = cursor.getCount();
        	comments = new Comment[count];
            cursor.moveToFirst();
            for(int i = 0; i < count; i++){
            	comments[i] = getComment(cursor);
                cursor.moveToNext();
            }
            this.mData = comments;
        } catch(Exception e){
        	comments = new Comment[0];
        } finally {
            db.close();
        }
        return comments;
	}

	public Comment[] findByContactId(int id) {
		return findByContactId(Integer.toString(id));
	}

	public Comment[] findByUserId(String id) {
		SQLiteDatabase db = mDataSource.getReadableDatabase();

		Comment[] comments = null;
        try {
            Cursor cursor = db.query( Comment.TABLE_NAME, null, Comment.USER_ID + "=?", new String[]{id}, null, null, null);
            int count = cursor.getCount();
        	comments = new Comment[count];
            cursor.moveToFirst();
            for(int i = 0; i < count; i++){
            	comments[i] = getComment(cursor);
                cursor.moveToNext();
            }
            this.mData = comments;
        } catch(Exception e){
        	comments = new Comment[0];
        } finally {
            db.close();
        }
        return comments;
	}

	public Comment[] findByUserId(int id) {
		return findByUserId(Integer.toString(id));
	}

	 private Comment getComment(Cursor cursor){
		 Comment comment = new Comment(
				 cursor.getLong(0),
				 cursor.getInt(1),
				 cursor.getInt(2),
				 cursor.getString(3),
				 cursor.getString(4),
				 cursor.getInt(7),
				 cursor.getInt(8),
				 cursor.getString(5),
				 cursor.getString(6)
		);
		 return comment;
	}
}
